package com.itheima.pratice.demo;

import java.util.Arrays;

public class MyArrayList<E> {//尝试实现ArrayList底层原理
    //创建Object数组
    private Object[] objects = {};
    //创建指针
    private int size;

    //add方法
    public boolean add(E e) {
        if (objects.length == size) {
            grow();
        }
        objects[size++] = e;
        return true;
    }

    //数组扩张方法
    private void grow() {
        //新数组
        int newLength;
        if (objects.length == 0) {//数组为0，新数组初始化为10
            newLength = 10;
        } else {
            newLength = objects.length + objects.length >> 1;//新数组扩展1.5倍
        }
        Object[] newObjects = new Object[newLength];
        System.arraycopy(objects, 0, newObjects, 0, objects.length);
        //objects指向新数组
        objects = newObjects;
    }

    //返回size方法
    public int size() {
        return size;
    }

    //获得指定索引元素
    public E get(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("索引" + index + "超过范围");
        }
        return (E) objects[index];
    }

    //toString方法重写

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < objects.length; i++) {
            if(objects[i] == null){//当前元素为空则不显示
                continue;
            }else if (i == size-1) {
                sb.append(objects[i]);
            }else{
                sb.append(objects[i]).append(", ");
            }
        }
        sb.append("]");
        return  sb.toString();
    }
}
